//
//  VoicePlayManager.m
//  BuxProject
//
//  Created by iOS的 on 2021/12/20.
//  Copyright © 2020 Moitnea. All rights reserved.
//

#import "VoicePlayManager.h"

@interface VoicePlayManager ()<AVAudioPlayerDelegate>

@property (nonatomic,copy) voicePlayRelevantBlock voicePlayBlock;

@end


@implementation VoicePlayManager

static VoicePlayManager *_shared;
+(instancetype)shareManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if(!_shared){
            _shared=[VoicePlayManager new];
        }
    });
    return _shared;
}

- (void)setPlayIndexrow:(NSInteger)playRow{
    _playIndexrow = playRow;
}

// 播放网络声音
-(void)voice_play:(NSString *)path withCompletionBlock:(voicePlayRelevantBlock)completionBlock{
    //
    self.voiceUrl = path;
    self.voicePlayBlock=completionBlock;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    NSError *error;
    _voicePlayer=[[AVAudioPlayer alloc]initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:path]] error:&error];
    if(!error){
        [_voicePlayer setNumberOfLoops:0];
        [_voicePlayer setDelegate:self];
        [_voicePlayer prepareToPlay];
        [_voicePlayer play];
    }else{
        !completionBlock?:completionBlock(@"播放失败",false);
    }
}
// 停止播放网络声音
-(void)play_stop{
    //
    if([_voicePlayer isPlaying]){
        [_voicePlayer stop];
    }
    self.voiceUrl = @"";
}
// 销毁
-(void)play_dealloc{
    if([_voicePlayer isPlaying]){
        [_voicePlayer stop];
    }
    if (_voicePlayer) {
        _voicePlayer = [AVAudioPlayer new];
    }
    self.voiceUrl = @"";
}

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    [self play_stop];
    !self.voicePlayBlock?:self.voicePlayBlock(flag?@"":@"播放失败",flag);
}
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error{
    !self.voicePlayBlock?:self.voicePlayBlock(@"播放失败",false);
}

-(void)dealloc{
    //
    [self play_dealloc];
}

@end
